<?php
/*
 * Created on 2011-2-19
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
 require_once('YiLook.php');
 class Generator{
 	
 	public $title;
 	private $chapterUrl;
 	public function __construct($chapterUrl) {
 		
		$this->title=YiLook::getTitleByChapter($chapterUrl);
		$this->chapterUrl=$chapterUrl;
		 		
 	}
 	
 	/**
 	 * 写入txt
 	 * @param string txt保存文件夹
 	 * @return mix 成功返回文件名，失败返回false
 	 */
 	public function write($path){
 		
 		//$temp=trim($path,'/').'/'.'_temp_'.time();
 		if(!is_writable($path)) throw new Exception('目录不可写');
 		
 		$temp = trim($path,'/').'/'.$this->title.'.txt';
 		$temp=iconv('utf-8','gbk',$temp);
 		
 		$chaptersArr=YiLook::getChapterList($this->chapterUrl);
 		//var_dump($chaptersArr);
 		
 		$content=$this->title."\r\n";
 		foreach ($chaptersArr as $v){
 			//	echo $v['contentUrl'],'<br />';
 			$content .= trim($v['chapter']."\n" .YiLook::getArticle($v['contentUrl'],true)) . "\n";
 					 				
 						
 		}
 		
 		//$content=mb_convert_encoding($content,'unicode','gbk,gb2312,utf-8');
 		//转成gbk，手机可读。
 		 $content=trim(iconv('UTF-8','gbk',$content)); //乱码问题，trim！
 		try {
 			
 			$fh=fopen($temp,'w');
 			fwrite($fh,$content);
 			fclose($fh);
 			
 			//file_put_contents($temp,$content);
 		}	catch (Exception $e) {
 			
 			//write to log if neccessary...
    		echo 'something wrong! ',  $e->getMessage(), "\n";
    		
    		return false;
    		
		}
 		
 		return $temp;
 		 		
 		
 	}
 	
 	
 }

